import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    Stock_BillListDto,
    StockZT_IntoBillItemServiceProxy,
    Stock_IntoToolingItemListDto,
    SessionServiceProxy,
    ComboboxItemDto,
    Stock_IntoToolingBaseExcelImportDto,
    Stock_IntoToolingBaseExcelImportOutput,
    Stock_IntoToolBaseExcelImportDto
} from '@shared/service-proxies/stock-service-proxies';

import { finalize } from 'rxjs/operators';
import { UserDataPermissionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { forEach, List } from 'lodash';
import { AppConsts } from '@shared/AppConsts';
import { CreateOrEditToolingIntoBillItemModalComponent } from './create-or-edit-tooling-into-bill-item-modal.component';

@Component({
    templateUrl: './tooling-into.component.html',
    animations: [appModuleAnimation()]
})
export class ToolingIntoComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;
    @ViewChild('createOrEditToolingIntoBillItemModal')
    createOrEditToolingIntoBillItemModal: CreateOrEditToolingIntoBillItemModalComponent;
    // filters
    materialNameFilter = '';
    materialCodeFilter = '';
    certificationNumFilter = '';
    reCheckFilter = '';
    supplierFilter = '';
    warehouseNameFilter = '';
    userDataPermissions;
    supplierList;
    inventBatchIDFilter = '';
    planNumberFilter = ''
    contractNumberFilter = '';
    f_DescriptionFilter = '';
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    selectedDepts;
    selectedSuppliers;
    f_isCurrentUser;
    detailPrimengTableHelper: PrimengTableHelper;
    optionbillBase = [{ label: '全部', value: undefined }, { label: '本人', value: '本人' }];
    selectedBill: Stock_BillListDto;
    selectedBillItem = new Stock_IntoToolingItemListDto();
    billItem;
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已入库', value: '已入库' },
        { label: '已审核', value: '已审核' }
    ];
    billstatus = '';
    billcode = '';
    constructor(
        injector: Injector,
        private _billService: StockZT_IntoBillItemServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _base_SessionServiceProxy: SessionServiceProxy
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
    }

    async ngOnInit() {
        let userResult = await this._userDataPermissionServiceProxy.getUserDataPermissions('Base_Bill').toPromise()
        this.userDataPermissions = userResult.items.map(e => {
            return {
                label: e.displayText,
                value: e
            };
        });




        //加载供应商数据
        let supplierResult = await this._billService.getStockToolingSupplierCombobox().toPromise()
        this.supplierList = supplierResult.items.map(e => {
            return {
                label: e.displayText,
                value: e
            };
        });
        this.selectedSuppliers = supplierResult.items;

        this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
            let ssData = new ComboboxItemDto();
            ssData.value = result.value;
            ssData.isSelected = false;
            ssData.displayText = result.label;
            let ss: ComboboxItemDto[] = [ssData];
            this.selectedDepts = ss;
            this.getBills();
        });

    }

    getBills(event?: LazyLoadEvent, resetpage?: boolean) {
        if (!this.selectedDepts) {
            return;
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            if (resetpage == undefined) {
                this.paginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getIntoToolingBaseListExtension(
                this.selectedDepts,
                this.selectedSuppliers,
                '',
                this.materialCodeFilter,
                this.materialNameFilter,
                this.billcode,
                this.billstatus,
                '',
                this.f_isCurrentUser,
                this.planNumberFilter,
                this.contractNumberFilter,
                this.f_DescriptionFilter,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_IntoToolingBaseList.totalCount;
                this.primengTableHelper.records = result.stock_IntoToolingBaseList.items;
                this.primengTableHelper.hideLoadingIndicator();

                this.detailPrimengTableHelper.totalRecordsCount = 0;
                this.detailPrimengTableHelper.records = null;

                this.selectedBill = null;
                this.selectedBillItem = null;
                console.log(result);
            });
    }

    submitBill() {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.totalRecordsCount <= 0) {
            this.message.warn('没有添加明细，不能提交');
            return;
        }
        this.message.confirm('确认提交该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .submitToolingIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success('提交成功');
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '已提交';
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    postBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认过账该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .postIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success('过账成功');
                        /* this.getBills(undefined, true); */
                        this.getIntoToolingBase();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    sendBackBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认退回该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .sendBackIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        /* this.getBills(undefined, true); */
                        this.selectedBill.f_BillStatus = '新建';
                        this.selectedBill.f_Posted = '未过账';
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    printBillList() {
        if (this.selectedBill === null || this.selectedBill.id === undefined) {
            this.notify.error('请选择需要打印的单据！');
        } else {
            //装配类派工单
            window.open(
                AppConsts.printAddr +
                '/webroot/decision/view/report?viewlet=erp/GJRKD.cpt&BillId=' +
                this.selectedBill.id
            );
        }
    }

    printAll() {
        window.open(AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/工装总库入库-汇总.cpt');
    }
    onUpload(event) {
        // let list = event as Array<any>;
        let list = event.fileData[0].sheetJson;
        console.log(list)
        let customerImportIntoList = list.map(el => {
            return {
                serialNumber: el.序号,
                deliveryDate: el.出库日期,
                materialCode: el.物料编码,
                name: el.名称,
                materialInformation: el.物资信息,
                model: el.型号,
                specifications: el.规格,
                accuracy: el.精度,
                brand: el.品牌,
                articleNumber: el.货号,
                unit: el.单位,
                firmOfferInventory: el.实盘库存数,
                unitPrice: el.单价,
                amountOfMoney: el.金额,
                supplier: el.供货单位,
                userDept: el.使用单位,
                remark: el.备注
            };
        }) as Array<Stock_IntoToolingBaseExcelImportDto>;
        this.message.confirm(
            '确认导入这' + customerImportIntoList.length + '条数据吗？',
            this.l('AreYouSure'),
            async (isConfirmed) => {
                if (isConfirmed) {
                    // this.primengTableHelper.showLoadingIndicator();
                    abp.ui.setBusy(undefined, `0 / ${customerImportIntoList.length}`);
                    let errorList = new Array<Stock_IntoToolingBaseExcelImportOutput>()
                    let currentIndex = 0
                    const IMPORT_STEP_LENGTH = 10
                    while (currentIndex < customerImportIntoList.length) {
                        let currentStepLength = IMPORT_STEP_LENGTH
                        if (customerImportIntoList.length - currentIndex < IMPORT_STEP_LENGTH) {
                            currentStepLength = customerImportIntoList.length - currentIndex
                        }
                        let result = await this.uploadStep(customerImportIntoList.slice(currentIndex, currentIndex + currentStepLength))
                        if (result && result.length > 0) {
                            errorList = errorList.concat(result)
                            console.log(result)
                        }
                        currentIndex += currentStepLength
                        abp.ui.setBusy(undefined, `${currentIndex} / ${customerImportIntoList.length}`);
                        console.log(`导入进度：${currentIndex} / ${customerImportIntoList.length}`)
                    }
                    abp.ui.clearBusy();
                    if (errorList.length > 0) {
                        //导出数据
                        console.log(errorList)
                        this.notify.error('部分导入成功');
                    } else {
                        this.notify.success('导入数据成功');
                    }
                    this.getBills()
                    // this.notify.success('导入数据成功');
                    // this.primengTableHelper.hideLoadingIndicator();
                }
            }
        );
    }
    uploadStep(list: Array<Stock_IntoToolingBaseExcelImportDto>) {
        return new Promise<Stock_IntoToolingBaseExcelImportOutput[]>((resolve, reject) => {
            this._billService
                .stock_IntoToolingImport(list)
                .subscribe(result => {
                    //this.getModels();
                    //this.notify.success('导入数据成功');
                    //this.primengTableHelper.hideLoadingIndicator();
                    resolve(result)
                });
        })
    }
    getBillItems(event?: LazyLoadEvent, clear?: boolean) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            if (clear == undefined) {
                this.detailPaginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getIntoToolingItemListExtension(
                this.selectedBill.id,
                '',
                '',
                '',
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.stock_IntoToolingItemList.totalCount;
                this.detailPrimengTableHelper.records = result.stock_IntoToolingItemList.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.billItem = result.stock_IntoToolingItemList.items;
                if (!clear) {
                    this.selectedBillItem = null;
                }
            });
    }

    deleteBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteIntoBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteIntoBillItem(this.selectedBillItem.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this._billService.updateBillItemSort(this.selectedBill.id).subscribe(() => {
                            this.notify.success(this.l('SuccessfullyDeleted'));

                            this.getBillItems();

                            this.primengTableHelper.hideLoadingIndicator();
                        });
                    });
            }
        });
    }
    //拆分
    splitBill() {
        if (!this.selectedBillItem) {
            return;
        }
        this.selectedBillItem.f_BillId = this.selectedBill.id;
        this.message.confirm('是否把当前入库明细拆分为' + this.selectedBillItem.f_Quantity + '条？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .splitToolingIntoBillItem(this.selectedBillItem)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBillItems();
                        this.selectedBillItem = undefined;
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    inserttooling(billid, event) {
        this.createOrEditToolingIntoBillItemModal.show(billid, undefined, event, this.selectedBillItem.id);
    }
    // 上移
    moveUp() {
        // console.log(this.selectedBill.f_BillStatus);
        if (!this.selectedBillItem) {
            return;
        }
        if (this.selectedBill.f_BillStatus != '新建') {
            this.notify.error('该单据状态不允许上移！');
            return;
        }

        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .moveUpIntoItem(this.selectedBillItem.id)
            .pipe(
                finalize(() => {
                    this.primengTableHelper.hideLoadingIndicator();
                })
            )
            .subscribe(() => {
                this.getBillItems(undefined, true);

                this.primengTableHelper.hideLoadingIndicator();
            });
    }
    // 下移
    moveDown() {
        if (!this.selectedBillItem) {
            return;
        }
        if (this.selectedBill.f_BillStatus != '新建') {
            this.notify.error('该单据状态不允许下移！');
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .moveDownIntoItem(this.selectedBillItem.id)
            .pipe(
                finalize(() => {
                    this.primengTableHelper.hideLoadingIndicator();
                })
            )
            .subscribe(() => {
                this.getBillItems(undefined, true);
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    //提交审核过账后，获取单据对应改变的信息（页面不刷新）
    getIntoToolingBase() {
        if (this.selectedBill == null || this.selectedBill.id == undefined) {
            return;
        }

        this.primengTableHelper.showLoadingIndicator();
        this._billService.getIntoToolingBaseById(this.selectedBill.id).subscribe(result => {
            this.selectedBill.f_BillStatus = result.f_BillStatus;
            this.selectedBill.f_Posted = result.f_Posted;
            this.selectedBill.f_Poster = result.f_Poster;

            this.primengTableHelper.hideLoadingIndicator();
        });
    }
}
